package com.ccm.demo.shiro;

import com.ccm.demo.model.SysMenu;
import com.ccm.demo.model.SysRole;
import com.ccm.demo.model.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

public class MyShiroRealm extends AuthorizingRealm {
	@Resource
	private UserInfoService userInfoService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		SysUser sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
		for (SysRole role : sysUser.getRoles()) {
			authorizationInfo.addRole(role.getRoleName());
			for (SysMenu menu : role.getMenus()) {
				authorizationInfo.addStringPermission(menu.getMenuUrl());
			}
		}
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		//获取用户的输入的账号.
		String username = (String) authenticationToken.getPrincipal();
		//通过username从数据库中查找 User对象，如果找到，没找到.
		//实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
		SysUser sysUser = userInfoService.findByUsername(username);
//        System.out.println("----->>userInfo="+userInfo);
		if (sysUser == null) {
			return null;
		}
		if (sysUser.getEnabled() == 0) { //账户冻结
			throw new LockedAccountException();
		}
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				sysUser, //用户名
				sysUser.getSysPassword(), //密码
				ByteSource.Util.bytes(sysUser.getCredentialsSalt()),//salt=username+salt
				getName()  //realm name
		);
		return authenticationInfo;
	}
}
